<template>
  <div class="sms-component">
    <span
      :class="[
        { disabled: isSending || disabled },
        { 'external-disabled': disabled }
      ]"
      @click="handleSendSMS"
    >
      {{ buttonText }}
    </span>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';

const props = defineProps({
  smsUrl: {
    type: String,
    default: '',
  },
  smsType: {
    type: String,
    default: 'default',
  },
  preAction: {
    type: Function,
    default: () => Promise.resolve(),
  },
  postAction: {
    type: Function,
    default: () => Promise.resolve(),
  },
  countdownSeconds: {
    type: Number,
    default: 60,
  },
  disabled: {
    type: Boolean,
    default: false,
  },
});

const isSending = ref(false);
const buttonText = ref('获取验证码');

const handleSendSMS = async () => {
  if (isSending.value || props.disabled) return;

  try {
    isSending.value = true;

    await props.preAction();

    const response = await fetch(props.smsUrl, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ type: props.smsType }),
    });

    const data = await response.json();
    console.log('SMS sent:', data);

    await props.postAction();
  } catch (error) {
    console.error('Error sending SMS:', error);
    isSending.value = false;
    return;
  }

  // Start countdown
  let time = props.countdownSeconds;
  buttonText.value = `${time}s`;
  const timer = setInterval(() => {
    time--;
    if (time > 0) {
      buttonText.value = `${time}s`;
    } else {
      clearInterval(timer);
      isSending.value = false;
      buttonText.value = '获取验证码';
    }
  }, 1000);
};
</script>

<style scoped>
.sms-component {
  display: inline-block;
  min-width: 80px;
  text-align: center;
}
.sms-component span {
  cursor: pointer;
  color: #333;
  font-weight: bold;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0 8px;
  transition: all 0.3s ease;
}
.sms-component span.disabled {
  cursor: not-allowed;
  color: #c0c4cc;
  font-weight: normal;
}
.sms-component span.external-disabled {
  color: #999 !important;
  border-radius: 4px;
  padding: 0 8px;
  font-weight: normal;
}
</style>
